package com.yulian.web_api.report;

import com.healthmarketscience.sqlbuilder.Conditions;
import com.healthmarketscience.sqlbuilder.CustomSql;
import com.healthmarketscience.sqlbuilder.InCondition;
import com.healthmarketscience.sqlbuilder.SelectQuery;
import com.yulian.repository.CommonRepositoryImpl;
import com.yulian.util.*;
import com.yulian.web_api.vo.SupplierInvoicingManagementVo;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.User;
import io.vertx.pgclient.PgPool;
import io.vertx.sqlclient.Tuple;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 该类位于业务逻辑层，主要实现商品毛利及提成管理报表数据查询，新增数据，更新数据，删除数据、导出、打印数据的业务逻辑，为MainVerticle中的REST接口提供服务
 *
 * @author
 */
public class SupplierInvoicingManagementManager {
    final InternalLogger logger = Log4JLoggerFactory.getInstance(SupplierInvoicingManagementManager.class);
    CommonRepositoryImpl commonRepository = new CommonRepositoryImpl();

    /**
     * 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getRecords(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传递的字段
        List<String> must_fields = Arrays.asList("goods_gather_area_id_list", "supplier_id_list", "legal_entity_id", "page_size", "page_index");
        JsonObject must = this.commonRepository.verifyAllParamMust(bodyJSObj, must_fields);
        if (must != null) {
            promise.complete(must);
            return promise.future();
        }
        //从bodyJson中获取数据
        String start_trade_date = bodyJSObj.getString("start_trade_date");
        String end_trade_date = bodyJSObj.getString("end_trade_date");
        String goods_gather_area_id_list = bodyJSObj.getString("goods_gather_area_id_list");
        String supplier_id_list = bodyJSObj.getString("supplier_id_list");
        String legal_entity_id = bodyJSObj.getString("legal_entity_id");

        int page_size = Integer.valueOf(bodyJSObj.getString("page_size"));
        int page_index = Integer.valueOf(bodyJSObj.getString("page_index"));
        int query_offset = (page_index - 1) * page_size;
        int query_limit = page_size;
        //数据是否为空校验
        if (DataUtils.isEmpty(goods_gather_area_id_list, supplier_id_list, legal_entity_id, page_size, page_index)) {
            promise.fail(CommonUtils.createExceptionJsonObjectStr(408, "参数 不合法"));
            return promise.future();
        }
        //用于传递给构建sql的JsonObject
        JsonObject queryJSObj = new JsonObject();
        queryJSObj.put("goods_gather_area_id", goods_gather_area_id_list);
        queryJSObj.put("supplier_id", supplier_id_list);
        queryJSObj.put("legal_entity_id", legal_entity_id);
        if (!start_trade_date.equals("") && start_trade_date!=null && !start_trade_date.equals("[]")){
            queryJSObj.put("start_trade_date", start_trade_date);
        }

        if (!end_trade_date.equals("") && end_trade_date!=null && !end_trade_date.equals("[]")){
            queryJSObj.put("end_trade_date", end_trade_date);
        }
        this.commonRepository.getCon(client).onSuccess(conn -> {
            String sql = createSelectSql(queryJSObj, query_offset, query_limit);
            this.commonRepository.queryJsonArray(conn, sql, "getSupplierInvoicingManagementRecords")
            .onSuccess(resJSArray -> { //resJSArray中就是获取到符合条件的数据
                //        取出每条记录中含code字段的值放入对应的集合
                List<SupplierInvoicingManagementVo> list =new ArrayList<>();
                for (int i = 0; i < resJSArray.size(); i++) {
                    JsonObject jsonObj = resJSArray.getJsonObject(i);
                    SupplierInvoicingManagementVo vo =new SupplierInvoicingManagementVo();
                    vo.setId(Integer.valueOf(jsonObj.getString("id")));

                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        Date date = format.parse(jsonObj.getString("time_axis"));
                        vo.setTimeAxis(date);
                    } catch (ParseException e) {
                        throw new RuntimeException(e);
                    }
                    vo.setGoodsGatherAreaId(Integer.valueOf(jsonObj.getString("goods_gather_area_id")));
                    vo.setGoodsGatherAreaName(jsonObj.getString("goods_gather_area_name"));
                    vo.setSupplierId(Integer.valueOf(jsonObj.getString("supplier_id")));
                    vo.setSupplierName(jsonObj.getString("supplier_name"));
                    vo.setLegalEntityId(Integer.valueOf(jsonObj.getString("legal_entity_id")));
                    vo.setLegalEntityName(jsonObj.getString("legal_entity_name"));
                    vo.setInvoicingDocumentCode(jsonObj.getString("invoicing_document_code"));
                    vo.setInvoicingCycleId(Integer.valueOf(jsonObj.getString("invoicing_cycle_id")));
                    vo.setTotalTaxableSalesAmountDemandOrders(jsonObj.getString("total_taxable_sales_amount_demand_orders"));
                    vo.setDemandOrderInputTaxRate(Double.parseDouble(jsonObj.getString("demand_order_input_tax_rate")));
                    vo.setDemandOrderInputTaxAmount(Double.parseDouble(jsonObj.getString("demand_order_input_tax_amount")));
                    vo.setInputTaxInvoiceCode(jsonObj.getString("input_tax_invoice_code"));
                    vo.setTotalTaxableSalesInvoicesAmount(Double.parseDouble(jsonObj.getString("total_taxable_sales_invoices_amount")));
                    vo.setInvoiceInputTaxRate(Double.parseDouble(jsonObj.getString("invoice_input_tax_rate")));
                    vo.setInvoiceInputTaxAmount(Double.parseDouble(jsonObj.getString("invoice_input_tax_amount")));
                    list.add(vo);
                }

                Map<Integer, List<SupplierInvoicingManagementVo>> newMap = list.stream().collect(Collectors.groupingBy(SupplierInvoicingManagementVo::getSupplierId));  //先按供应商ID
                newMap.forEach((key, value) -> {
                    Map<Integer, List<SupplierInvoicingManagementVo>> newMap2 = value.stream().collect(Collectors.groupingBy(SupplierInvoicingManagementVo::getInvoicingCycleId));  //按周期ID
                    newMap2.forEach((key2, value2) -> {
                        double a1=0.00;
                        double a2=0.00;
                        for (SupplierInvoicingManagementVo vo:value2){
                            //需求单进项税额
                            double b1=  vo.getDemandOrderInputTaxAmount();
                            double b2=  vo.getInvoiceInputTaxAmount();
                            BigDecimal bigDecimal1=new BigDecimal(b1);
                            BigDecimal bigDecimal11=new BigDecimal(a1);
                            a1 =bigDecimal11.add(bigDecimal1).doubleValue();

                            BigDecimal bigDecimal2=new BigDecimal(b2);
                            BigDecimal bigDecimal21=new BigDecimal(a2);
                            a2=bigDecimal21.add(bigDecimal2).doubleValue();
                        }
                        BigDecimal c1 =new BigDecimal(a1);
                        BigDecimal c2 =new BigDecimal(a2);
                        double a3=c2.subtract(c1).doubleValue();
                        for (SupplierInvoicingManagementVo vo:value2){
                            //需求单进项税额
                            vo.setOnlineCumulativeDemandOrderInputTaxAmount(a1);
                            vo.setOnlineCumulativeInvoiceInputTaxAmount(a2);
                            vo.setAccumulatedDifferenceInputTaxPayable(a3);
                        }
                    });
                });
                JsonObject dataJSObj = new JsonObject();
                dataJSObj.put("total", list.size()).put("records", list);
                responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                promise.complete(responseJSObj);
            }).onFailure(err -> promise.complete(CommonUtils.createExceptionJsonObject(err, "getSupplierInvoicingManagementRecords", "获取供应商开票管理失败")));
        }).onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getSupplierInvoicingManagementRecords", "数据库连接失败")));
        return promise.future();
    }


    /**
     * 创建查询符合搜索条件记录的sql语句
     *
     * @param queryJS      body参数对象
     * @param query_offset 页面偏移
     * @param query_limit  页面记录数
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSql(JsonObject queryJS, int query_offset, int query_limit) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("time_axis"), new CustomSql("goods_gather_area_id"), new CustomSql(" (select gga.goods_gather_area_name " +
                                "           from goods_gather_area gga " +
                                "           where gga.is_delete=0 " +
                                "           and gga.id=goods_gather_area_id " +
                                "           )as goods_gather_area_name "), new CustomSql("supplier_id"), new CustomSql("(select supplier_name " +
                                "        from supplier_info si " +
                                "        where si.is_delete=0 " +
                                "        and si.id=supplier_id) as supplier_name "),new CustomSql("legal_entity_id"),new CustomSql("  (select pe.legal_entity_name " +
                                "        from payment_entity pe " +
                                "        where pe.is_delete=0 " +
                                "        and pe.id=legal_entity_id) as legal_entity_name"),new CustomSql("invoicing_document_code"),new CustomSql("invoicing_cycle_id"),new CustomSql("total_taxable_sales_amount_demand_orders"),
                        new CustomSql("demand_order_input_tax_rate"), new CustomSql("demand_order_input_tax_amount"),new CustomSql("input_tax_invoice_code"),new CustomSql("total_taxable_sales_invoices_amount"),new CustomSql("invoice_input_tax_rate"),
                        new CustomSql("invoice_input_tax_amount"),
                        new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
        .addCustomFromTable("supplier_invoicing_management");
       Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if ("start_trade_date".equals(key)) {
                    sq.getWhereClause().addCustomCondition(Conditions.greaterThanOrEq(new CustomSql("create_time"),
                    TimeUtils.parseLocalDate(value, "yyyy-MM-dd")).setDisableParens(true));
                    continue;
                } else if ("end_trade_date".equals(key)) {
                    sq.getWhereClause().addCustomCondition(Conditions.lessThanOrEq(new CustomSql("create_time"),
                    TimeUtils.parseLocalDate(value, "yyyy-MM-dd")).setDisableParens(true));
                    continue;
                }
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where InCondtion子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc limit " + query_limit + " offset " + query_offset;
    }



    /**
     * 该方法实现接收web前端通过body传入的参数，调用数据访问层CommonParameterRepositoryImpl 类的方法实现数据的增、删、改。
     * 通过含参数的Json对象bodyJSObj，通过method字段获取操作类型，分别是insert，update, delete
     * 1) 操作类型为 insert，新增数据
     * 2）操作类型为 update，更新数据
     * 3）操作类型为 delete，逻辑删除多条记录
     * 调用TransportRevenueerRepositoryImpl 的方法
     *
     * @param client
     * @param bodyJSObj
     * @param user
     * @return
     */
    public Future<JsonObject> insertOrUpdate(PgPool client, JsonObject bodyJSObj, User user,JsonObject config) {
        Promise<JsonObject> promise = Promise.promise();
        int user_id = user.attributes().getJsonObject("accessToken").getInteger("userId");
        long create_user = Long.parseLong(user.attributes().getJsonObject("accessToken").getString("username"));
        //最后返回的json对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传递的非数值字段
        List<String> must_fields = Arrays.asList("method","invoicing_cycle_id","input_tax_invoice_code","demand_order_input_tax_rate","total_taxable_sales_invoices_amount","invoice_input_tax_rate");
        JsonObject must = this.commonRepository.verifyAllParamMust(bodyJSObj, must_fields);
        if (must != null) {
            promise.complete(must);
            return promise.future();
        }
        // 验证必须传递的数字字段
        List<String> numeric_fields = Arrays.asList("invoicing_cycle_id","demand_order_input_tax_rate");
        JsonObject numeric = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields);
        if (numeric != null) {
            promise.complete(numeric);
            return promise.future();
        }
        String method = bodyJSObj.getString("method");
        logger.info("method {}", method);
        if (method.equals("insert")){
            //新增的
            // 验证必须传递的非数值字段
            List<String> must_fields2 = Arrays.asList("goods_gather_area_id", "supplier_id","legal_entity_id","invoicing_cycle_id");
            JsonObject must2 = this.commonRepository.verifyAllParamMust(bodyJSObj, must_fields2);
            if (must2 != null) {
                promise.complete(must2);
                return promise.future();
            }
            // 验证必须传递的数字字段
            List<String> numeric_fields2 = Arrays.asList("goods_gather_area_id", "legal_entity_id","supplier_id","invoicing_cycle_id");
            JsonObject numeric2 = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields2);
            if (numeric2 != null) {
                promise.complete(numeric2);
                return promise.future();
            }
        }else if (method.equals("update")){
            //编辑
            // 验证必须传递的非数值字段
            List<String> must_fields2 = Arrays.asList("id","legal_entity_id");
            JsonObject must2 = this.commonRepository.verifyAllParamMust(bodyJSObj, must_fields2);
            if (must2 != null) {
                promise.complete(must2);
                return promise.future();
            }
            // 验证必须传递的数字字段
            List<String> numeric_fields2 = Arrays.asList("id","legal_entity_id");
            JsonObject numeric2 = this.commonRepository.verifyAllParamNumeric(bodyJSObj, numeric_fields2);
            if (numeric2 != null) {
                promise.complete(numeric2);
                return promise.future();
            }
        }

        this.commonRepository.getCon(client).onSuccess(conn -> {
            if (method.equals("insert")) {
                Long invoicing_cycle_id2 = Long.valueOf(bodyJSObj.getString("invoicing_cycle_id"));
                String invoice_cycle_sql = "select cycle_name from invoice_cycle where 1=1 and id =$1 limit 1";
                this.commonRepository.getCodeFuture(conn, invoice_cycle_sql,Tuple.of(invoicing_cycle_id2),"getInvoiceCycleFuture", "供应商的开票周期 操作失败")
                        .onComplete(ar3->{
                            if (ar3.succeeded()){
                                //查询成功
                                String cycle_name = ar3.result().toString();
                                JsonObject cycle_name_info = config.getJsonObject("CYCLE_NAME");
                                List<String> dates =new ArrayList<>();
                                try {
                                    dates=DateUtils.calculateDate(cycle_name,cycle_name_info);
                                } catch (ParseException e) {
                                    //计算时间周期失败
                                    promise.fail(CommonUtils.createExceptionJsonObjectStr(ar3, "calculateDate", "计算时间周期失败"));
                                }

                                Long legal_entity_id = Long.parseLong(bodyJSObj.getString("legal_entity_id"));
                                Long goods_gather_area_id = Long.valueOf(bodyJSObj.getString("goods_gather_area_id"));
                                Long supplier_id = Long.valueOf(bodyJSObj.getString("supplier_id"));
                                Long invoicing_cycle_id = Long.valueOf(bodyJSObj.getString("invoicing_cycle_id"));
                                String input_tax_invoice_code= bodyJSObj.getString("input_tax_invoice_code");
                                double demand_order_input_tax_rate = Double.parseDouble(bodyJSObj.getString("demand_order_input_tax_rate"));
                                double total_taxable_sales_invoices_amount = Double.parseDouble(bodyJSObj.getString("total_taxable_sales_invoices_amount").equals("")? "0":bodyJSObj.getString("total_taxable_sales_invoices_amount"));
                                double invoice_input_tax_rate = Double.parseDouble(bodyJSObj.getString("invoice_input_tax_rate").equals("")? "0":bodyJSObj.getString("invoice_input_tax_rate"));


                                List<Future> futureList = new ArrayList<>();
                                String goods_gather_area_sql = "select goods_gather_area_name from goods_gather_area where id = $1 and is_delete = 0 limit 1";
                                Future<String> goodsGatherAreaFuture = this.commonRepository.getCodeFuture(conn, goods_gather_area_sql, Tuple.of(goods_gather_area_id),"select_goods_gather_area", "供应商商品聚集区名查询 操作失败\"");
                                futureList.add(goodsGatherAreaFuture);

                                String supplier_id_sql = "select supplier_name from supplier_info where id = $1 and is_delete = 0 limit 1";
                                Future<String> supplierFuture = this.commonRepository.getCodeFuture(conn, supplier_id_sql, Tuple.of(supplier_id), "supplier_id_sql", "供应商名查询 操作失败");
                                futureList.add(supplierFuture);

                                String class_code_sql = "select seq from supplier_invoicing_management where 1=1 order by id desc limit 1";
                                Future<String> getClassCodeFuture = this.commonRepository.getCodeFuture(conn, class_code_sql,"seq", "供应商开票管理主表的顺序号 操作失败");
                                futureList.add(getClassCodeFuture);

                                //供应商提货计划支付单
                                String sppp_sql = "select supplier_pickup_plan_payment_code,payment_total_amount from supplier_pickup_plan_payment where is_delete=0 and supplier_id=$1 and payment_date >= '"+dates.get(0)+"' and payment_date < '"+dates.get(1)+"' and supplier_pickup_plan_payment_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        "    ) ";
                                Future<JsonArray> getSpppFuture = this.commonRepository.queryJsonArray(conn, sppp_sql,Tuple.of(supplier_id), "供应商提货计划支付单 操作失败");
                                futureList.add(getSpppFuture);

//                                //供应商提货计划支付差异单
//                                String spppd_sql = "select supplier_pickup_plan_payment_difference_code,payment_difference_amount from supplier_pickup_plan_payment_diff where is_delete=0 and supplier_id=$1 and generate_date >= '"+dates.get(0)+"' and generate_date < '"+dates.get(1)+"' and supplier_pickup_plan_payment_difference_code not in ( " +
//                                        "    select payment_order_code " +
//                                        "    from supplier_invoicing_management_detail " +
//                                        "    where 1=1 " +
//                                        "    ) ";

                                //供应商提货计划支付差异单
                                String spppd_sql = "select bpplcd.supplier_pickup_plan_payment_diff_code,spppd.real_pickup_number,spppd.real_settlement_package_spec,spppd.settlement_price,bpplcd.real_goods_grade_pickup_plan_number " +
                                        "from batch_pickup_plan_load_completion_detail bpplcd left join supplier_pickup_plan_payment_detail  spppd  on " +
                                        "    bpplcd.supplier_pickup_plan_payment_detail_id=spppd.id " +
                                        "where bpplcd.is_delete=0 and bpplcd.supplier_id=$1 " +
                                        "  and bpplcd.generate_date >= '"+dates.get(0)+"'" +
                                        "  and bpplcd.generate_date < '"+dates.get(1)+"' " +
                                        "  and bpplcd.supplier_pickup_plan_payment_diff_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 ) ";
                                Future<JsonArray> getSpppdFuture = this.commonRepository.queryJsonArray(conn, spppd_sql,Tuple.of(supplier_id), "供应商提货计划支付差异单 操作失败");
                                futureList.add(getSpppdFuture);

                                //供应商退货通知单支付差异单
                                String srnpd_sql = "select supplier_return_notice_payment_diff_code, " +
                                        "( select s.settlement_price " +
                                        "    from supplier_pickup_plan_payment_detail s " +
                                        "    where s.is_delete=0 " +
                                        "    and s.id= " +
                                        "    ( select b.supplier_pickup_plan_payment_detail_id " +
                                        "    from real_pickup_plan_number_allocation b " +
                                        "    where b.is_delete=0 " +
                                        "    and b.id=(    select a.real_pickup_plan_number_allocation_id " +
                                        "                  from supplier_pickup_goods_inspect_accept_detail a " +
                                        "                  where a.is_delete=0 " +
                                        "                    and a.id=supplier_pickup_goods_inspect_accept_detail_id) " +
                                        "    )) as settlement_price, " +
                                        "    (    select a.unqualify_goods_weight " +
                                        "         from supplier_pickup_goods_inspect_accept_detail a " +
                                        "         where a.is_delete=0 " +
                                        "           and a.id=supplier_pickup_goods_inspect_accept_detail_id) as unqualify_goods_weight" +
                                        " from supplier_return_notice_payment_diff where is_delete=0 and supplier_id=$1 and generate_date >= '"+dates.get(0)+"' and generate_date < '"+dates.get(1)+"' and supplier_return_notice_payment_diff_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        "    ) ";
                                Future<JsonArray> getSrnpdFuture = this.commonRepository.queryJsonArray(conn, srnpd_sql,Tuple.of(supplier_id), "供应商退货通知单支付差异单 操作失败");
                                futureList.add(getSrnpdFuture);

                                //供应商入库通知单支付差异单
                                String swpd_sql = "select supplier_warehouse_payment_diff_code," +
                                        "        (select a.payment_total_amount " +
                                        "        from supplier_pickup_plan_payment a " +
                                        "        where a.is_delete=0 " +
                                        "        and a.id=supplier_pickup_plan_payment_id)as payment_total_amount, " +
                                        "      (select (a.total_weight-(a.total_number*(select gpscg.supply_chain_goods_package_weight from goods_parameter_supply_chain_goods gpscg  where gpscg.is_delete=0 and gpscg.id=a.goods_parameter_supply_chain_goods_id))) as weight " +
                                        "   from supplier_pickup_goods_inspect_accept_detail a " +
                                        "      where a.is_delete=0 " +
                                        " and a.id=supplier_pickup_goods_inspect_accept_detail_id ) as accept_total_weight, " +
                                        "       ( select s.settlement_price " +
                                        "           from supplier_pickup_plan_payment_detail s " +
                                        "           where s.is_delete=0 " +
                                        "             and s.id= " +
                                        "                 ( select b.supplier_pickup_plan_payment_detail_id " +
                                        "                     from real_pickup_plan_number_allocation b " +
                                        "                     where b.is_delete=0 " +
                                        "                       and b.id=(    select a.real_pickup_plan_number_allocation_id " +
                                        "                                     from supplier_pickup_goods_inspect_accept_detail a " +
                                        "                                     where a.is_delete=0 " +
                                        "                                       and a.id=supplier_pickup_goods_inspect_accept_detail_id) " +
                                        "                 ) " +
                                        "       ) as settlement_price" +
                                        " from supplier_warehouse_payment_diff where is_delete=0 and supplier_id=$1 and generate_date >= '"+dates.get(0)+"' and generate_date < '"+dates.get(1)+"' and supplier_warehouse_payment_diff_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        "    ) ";
                                Future<JsonArray> getSwpdFuture = this.commonRepository.queryJsonArray(conn, swpd_sql,Tuple.of(supplier_id), "供应商入库通知单支付差异单 操作失败");
                                futureList.add(getSwpdFuture);

                                //供应商赔偿单
                                String sc_sql = "select supplier_compensation_code,unqualify_compensation_affirm_amount from supplier_compensation where is_delete=0 and supplier_id=$1 and generate_date >= '"+dates.get(0)+"' and generate_date < '"+dates.get(1)+"' and supplier_compensation_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        "    ) ";
                                Future<JsonArray> getScFuture = this.commonRepository.queryJsonArray(conn, sc_sql,Tuple.of(supplier_id), "供应商赔偿单 操作失败");
                                futureList.add(getScFuture);

                                //销售地-供应商提货计划支付单
                                String ssppp_sql = "select supplier_pickup_plan_payment_code, " +
                                        "        ( select sum(appc.real_settlement_package_spec::numeric*appc.real_settlement_price::numeric*appc.real_transaction_number::numeric) as payment_total_amount " +
                                        "               from sales_pickup_plan_command appc " +
                                        "              where appc.is_delete=0 " +
                                        "              and appc.id in " +
                                        "           (  select sales_pickup_plan_command_id " +
                                        "           from sales_supplier_pickup_plan_payment_detail sd " +
                                        "           where sd.is_delete=0 " +
                                        "           and sd.id=id " +
                                        "           ) " +
                                        "        ) as payment_total_amount" +
                                        "    from sales_supplier_pickup_plan_payment where is_delete=0 and supplier_id=$1 and payment_date >= '"+dates.get(0)+"' and payment_date < '"+dates.get(1)+"'  and supplier_pickup_plan_payment_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        "    ) ";
                                Future<JsonArray> getSspppFuture = this.commonRepository.queryJsonArray(conn, ssppp_sql,Tuple.of(supplier_id), "销售地-供应商提货计划支付单 操作失败");
                                futureList.add(getSspppFuture);

                                //销售地-供应商退货通知单支付差异单
                                String ssrnpd_sql = "select supplier_return_notice_payment_diff_code , " +
                                        "    (    select a.unqualify_goods_weight " +
                                        "            from sales_supplier_pickup_goods_inspect_accept_detail a " +
                                        "            where a.is_delete=0 " +
                                        "              and a.id=sales_supplier_pickup_goods_inspect_accept_detail_id) as unqualify_goods_weight, " +
                                        "( select b.real_settlement_price " +
                                        "        from sales_pickup_plan_command b " +
                                        "            where b.is_delete=0 " +
                                        "            and b.id= " +
                                        "           (    select a.sales_pickup_plan_command_id " +
                                        "                from sales_supplier_pickup_goods_inspect_accept_detail a " +
                                        "                where a.is_delete=0 " +
                                        "                  and a.id=sales_supplier_pickup_goods_inspect_accept_detail_id) " +
                                        "           )as real_settlement_price" +
                                        " from sales_supplier_return_notice_payment_diff where is_delete=0 and supplier_id=$1 and generate_date >= '"+dates.get(0)+"' and generate_date < '"+dates.get(1)+"' and supplier_return_notice_payment_diff_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        "    ) ";
                                Future<JsonArray> getSsrnpdFuture = this.commonRepository.queryJsonArray(conn, ssrnpd_sql,Tuple.of(supplier_id), "销售地-供应商退货通知单支付差异单 操作失败");
                                futureList.add(getSsrnpdFuture);

                                //销售地-供应商入库通知单支付差异单
                                String sswpd_sql = "select supplier_warehouse_payment_diff_code, " +
                                        "  ( select sum(appc.real_settlement_package_spec::numeric*appc.real_settlement_price::numeric*appc.real_transaction_number::numeric) as payment_total_amount " +
                                        "    from sales_pickup_plan_command appc " +
                                        "    where appc.is_delete=0 " +
                                        "      and appc.id in " +
                                        "    (  select b.sales_pickup_plan_command_id " +
                                        "        from sales_supplier_pickup_plan_payment_detail b " +
                                        "        where b.is_delete=0 " +
                                        "        and b.sales_supplier_pickup_plan_payment_id=( " +
                                        "        select a.id " +
                                        "        from sales_supplier_pickup_plan_payment a " +
                                        "        where a.is_delete=0 " +
                                        "        and a.id=sales_supplier_pickup_plan_payment_id " +
                                        "        )   )  )as payment_total_amount, " +
                                        "       (select (a.total_weight-(a.total_number*(select gpscg.supply_chain_goods_package_weight from goods_parameter_supply_chain_goods gpscg  where gpscg.is_delete=0 and gpscg.id=a.goods_parameter_supply_chain_goods_id))) as weight " +
                                        "  from sales_supplier_pickup_goods_inspect_accept_detail a " +
                                        "  where a.is_delete=0 " +
                                        "   and a.id=sales_supplier_pickup_goods_inspect_accept_detail_id ) as accept_total_weight, " +
                                        "       ( select b.real_settlement_price " +
                                        "            from sales_pickup_plan_command b " +
                                        "            where b.is_delete=0" +
                                        "            and b.id=(   select a.sales_pickup_plan_command_id " +
                                        "                        from sales_supplier_pickup_goods_inspect_accept_detail a " +
                                        "                        where a.is_delete=0 " +
                                        "                        and a.id=sales_supplier_pickup_goods_inspect_accept_detail_id) " +
                                        "       ) as real_settlement_price " +
                                        " from sales_supplier_warehouse_payment_diff where is_delete=0 and supplier_id=$1 and generate_date >= '"+dates.get(0)+"' and generate_date < '"+dates.get(1)+"' and supplier_warehouse_payment_diff_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        "    ) ";
                                Future<JsonArray> getSswpdFuture = this.commonRepository.queryJsonArray(conn, sswpd_sql,Tuple.of(supplier_id), "销售地-供应商入库通知单支付差异单 操作失败");
                                futureList.add(getSswpdFuture);

                                //销售地-供应商赔偿单
                                String ssc_sql = "select supplier_compensation_code,unqualify_compensation_affirm_amount from sales_supplier_compensation where is_delete=0 and supplier_id=$1 and generate_date >= '"+dates.get(0)+"' and generate_date < '"+dates.get(1)+"' and supplier_compensation_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        "    ) ";
                                Future<JsonArray> getSscFuture = this.commonRepository.queryJsonArray(conn, ssc_sql,Tuple.of(supplier_id), "销售地-供应商赔偿单 操作失败");
                                futureList.add(getSscFuture);

                                //明细所需要保存字段的值


                                //供应商提货计划支付
                                String d_sql1 = "select aggregation_id,real_payment_amount, " +
                                        " (select sppp.supplier_pickup_plan_payment_code " +
                                        "                                         from supplier_pickup_plan_payment sppp " +
                                        "                                         where sppp.is_delete=0 " +
                                        "                                         and sppp.id=supplier_pickup_plan_payment_id) as supplier_pickup_plan_payment_code " +
                                        "from supplier_pickup_plan_payment_detail " +
                                        "where is_delete=0 " +
                                        "and supplier_pickup_plan_payment_id in ( " +
                                        "select id " +
                                        "from supplier_pickup_plan_payment " +
                                        "where is_delete=0 and supplier_id=$1 " +
                                        "  and payment_date >= '"+dates.get(0)+"' " +
                                        "  and payment_date < '"+dates.get(1)+"' " +
                                        "  and supplier_pickup_plan_payment_code not in ( " +
                                        "    select b.payment_order_code " +
                                        "    from supplier_invoicing_management_detail b " +
                                        "    where 1=1 " +
                                        ")) ";
                                Future<JsonArray> getDetitleFuture1 = this.commonRepository.queryJsonArray(conn, d_sql1,Tuple.of(supplier_id), "供应商提货计划支付 操作失败");
                                futureList.add(getDetitleFuture1);

                                //供应商提货计划支付差异单
                                String d_sql2 = "select b.aggregation_id,b.payment_difference_amount,b.supplier_pickup_plan_payment_difference_code " +
                                        "from supplier_pickup_plan_payment_diff b " +
                                        "where b.is_delete=0 and b.supplier_id=$1 " +
                                        "  and b.generate_date >= '"+dates.get(0)+"'  " +
                                        "  and b.generate_date < '"+dates.get(1)+"' " +
                                        "  and b.supplier_pickup_plan_payment_difference_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        ") ";
                                Future<JsonArray> getDetitleFuture2 = this.commonRepository.queryJsonArray(conn, d_sql2,Tuple.of(supplier_id), "供应商提货计划支付差异单 操作失败");
                                futureList.add(getDetitleFuture2);

                                //供应商退货通知单支付差异单
                                String d_sql3 = "select b.aggregation_id, " +
                                        "     ( select s.settlement_price " +
                                        "           from supplier_pickup_plan_payment_detail s " +
                                        "           where s.is_delete=0 " +
                                        "             and s.id= " +
                                        "                 ( select br.supplier_pickup_plan_payment_detail_id " +
                                        "                     from real_pickup_plan_number_allocation br " +
                                        "                     where br.is_delete=0 " +
                                        "                       and br.id=(    select a.real_pickup_plan_number_allocation_id " +
                                        "                                     from supplier_pickup_goods_inspect_accept_detail a " +
                                        "                                     where a.is_delete=0 " +
                                        "                                       and a.id=b.supplier_pickup_goods_inspect_accept_detail_id))) as settlement_price, " +
                                        "       (    select a.unqualify_goods_weight " +
                                        "            from supplier_pickup_goods_inspect_accept_detail a " +
                                        "            where a.is_delete=0 " +
                                        "              and a.id=b.supplier_pickup_goods_inspect_accept_detail_id) as unqualify_goods_weight, " +
                                        " b.supplier_return_notice_payment_diff_code " +
                                        "from supplier_return_notice_payment_diff b " +
                                        "where b.is_delete=0 and b.supplier_id=$1 " +
                                        "  and b.generate_date >= '"+dates.get(0)+"' " +
                                        "  and b.generate_date < '"+dates.get(1)+"' " +
                                        "  and b.supplier_return_notice_payment_diff_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        ") ";
                                Future<JsonArray> getDetitleFuture3 = this.commonRepository.queryJsonArray(conn, d_sql3,Tuple.of(supplier_id), "供应商退货通知单支付差异单 操作失败");
                                futureList.add(getDetitleFuture3);

                                //供应商入库通知单支付差异单
                                String d_sql4 = "select b.aggregation_id, " +
                                        "     (select a.payment_total_amount " +
                                        "        from supplier_pickup_plan_payment a " +
                                        "        where a.is_delete=0\n" +
                                        "          and a.id=b.supplier_pickup_plan_payment_id)as payment_total_amount, " +
                                        "      (select (a.total_weight-(a.total_number*(select gpscg.supply_chain_goods_package_weight from goods_parameter_supply_chain_goods gpscg  where gpscg.is_delete=0 and gpscg.id=a.goods_parameter_supply_chain_goods_id))) as weight " +
                                        "   from supplier_pickup_goods_inspect_accept_detail a " +
                                        "      where a.is_delete=0 " +
                                        " and a.id=supplier_pickup_goods_inspect_accept_detail_id ) as accept_total_weight, " +
                                        "       (  select s.settlement_price " +
                                        "           from supplier_pickup_plan_payment_detail s " +
                                        "           where s.is_delete=0 " +
                                        "             and s.id= " +
                                        "                 (  select ba.supplier_pickup_plan_payment_detail_id " +
                                        "                     from real_pickup_plan_number_allocation ba " +
                                        "                     where ba.is_delete=0 " +
                                        "                       and ba.id=(    select a.real_pickup_plan_number_allocation_id " +
                                        "                                     from supplier_pickup_goods_inspect_accept_detail a " +
                                        "                                     where a.is_delete=0 " +
                                        "                                       and a.id=b.supplier_pickup_goods_inspect_accept_detail_id) " +
                                        "                 ) " +
                                        "       ) as settlement_price, " +
                                        "b.supplier_warehouse_payment_diff_code " +
                                        "from supplier_warehouse_payment_diff b " +
                                        "where b.is_delete=0  and b.supplier_id=$1 " +
                                        "  and b.generate_date >=  '"+dates.get(0)+"' " +
                                        "  and b.generate_date <  '"+dates.get(1)+"' " +
                                        "  and b.supplier_warehouse_payment_diff_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        ") ";
                                Future<JsonArray> getDetitleFuture4 = this.commonRepository.queryJsonArray(conn, d_sql4,Tuple.of(supplier_id), "供应商入库通知单支付差异单 操作失败");
                                futureList.add(getDetitleFuture4);

                                //供应商赔偿单
                                String d_sql5 = "select b.aggregation_id,b.unqualify_compensation_affirm_amount,b.supplier_compensation_code " +
                                        "from supplier_compensation b " +
                                        "where b.is_delete=0  and b.supplier_id=$1 " +
                                        "  and b.generate_date >= '"+dates.get(0)+"' " +
                                        "  and b.generate_date < '"+dates.get(1)+"' " +
                                        "  and b.supplier_compensation_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        ") ";
                                Future<JsonArray> getDetitleFuture5 = this.commonRepository.queryJsonArray(conn, d_sql5,Tuple.of(supplier_id), "供应商赔偿单 操作失败");
                                futureList.add(getDetitleFuture5);

                                //销售区-供应商提货计划支付单
                                String d_sql6 = "select aggregation_id,  " +
                                        " (select sppp.supplier_pickup_plan_payment_code " +
                                        "                                         from sales_supplier_pickup_plan_payment sppp " +
                                        "                                         where sppp.is_delete=0 " +
                                        "                                         and sppp.id=sales_supplier_pickup_plan_payment_id) as supplier_pickup_plan_payment_code , " +
                                        "        ( select sum(sppc.real_settlement_package_spec::numeric*sppc.real_settlement_price::numeric*sppc.real_transaction_number::numeric) as settlement_amount " +
                                        "           from sales_pickup_plan_command sppc " +
                                        "           where sppc.is_delete=0 " +
                                        "           and sppc.id=sales_pickup_plan_command_id " +
                                        "           )as settlement_amount " +
                                        " from sales_supplier_pickup_plan_payment_detail " +
                                        " where is_delete=0 " +
                                        "  and sales_supplier_pickup_plan_payment_id in ( " +
                                        "    select a.id " +
                                        "    from sales_supplier_pickup_plan_payment a " +
                                        "    where a.is_delete=0 and a.supplier_id=$1 " +
                                        "      and a.payment_date >= '"+dates.get(0)+"' " +
                                        "      and a.payment_date < '"+dates.get(1)+"' " +
                                        "      and a.supplier_pickup_plan_payment_code not in ( " +
                                        "        select b.payment_order_code " +
                                        "        from supplier_invoicing_management_detail b " +
                                        "        where 1=1 " +
                                        "    )) ";
                                Future<JsonArray> getDetitleFuture6 = this.commonRepository.queryJsonArray(conn, d_sql6,Tuple.of(supplier_id), "销售区-供应商提货计划支付单 操作失败");
                                futureList.add(getDetitleFuture6);

                                //销售区-供应商退货通知单支付差异单
                                String d_sql7 = "select b.aggregation_id,b.supplier_return_notice_payment_diff_code, " +
                                        "    (select a.return_goods_total_weight " +
                                        "        from sales_supplier_pickup_goods_inspect_accept_detail a " +
                                        "        where a.is_delete=0 " +
                                        "        and a.id=sales_supplier_pickup_goods_inspect_accept_detail_id " +
                                        "           )as return_goods_total_weight, " +
                                        "       (select b.real_settlement_price " +
                                        "               from sales_pickup_plan_command b " +
                                        "                   where b.is_delete=0 " +
                                        "                   and b.id= " +
                                        "           (select a.sales_pickup_plan_command_id " +
                                        "            from sales_supplier_pickup_goods_inspect_accept_detail a " +
                                        "            where a.is_delete = 0 " +
                                        "              and a.id = sales_supplier_pickup_goods_inspect_accept_detail_id)) as real_settlement_price" +
                                        " from sales_supplier_return_notice_payment_diff b " +
                                        " where b.is_delete=0 and b.supplier_id=$1 " +
                                        "  and b.generate_date >= '"+dates.get(0)+"' " +
                                        "  and b.generate_date < '"+dates.get(1)+"' " +
                                        "  and b.supplier_return_notice_payment_diff_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        ") ";
                                Future<JsonArray> getDetitleFuture7 = this.commonRepository.queryJsonArray(conn, d_sql7,Tuple.of(supplier_id), "销售区-供应商退货通知单支付差异单 操作失败");
                                futureList.add(getDetitleFuture7);

                                //销售区-供应商入库通知单支付差异单
                                String d_sql8 = "select b.aggregation_id,b.supplier_warehouse_payment_diff_code,  " +
                                        "        (select sum(sppc.real_settlement_package_spec::numeric*sppc.real_settlement_price::numeric*sppc.real_transaction_number::numeric) as settlement_amount " +
                                        "           from sales_pickup_plan_command  sppc " +
                                        "               where sppc.is_delete=0 " +
                                        "               and sppc.id in " +
                                        "           (select ss.sales_pickup_plan_command_id " +
                                        "        from sales_supplier_pickup_plan_payment_detail ss " +
                                        "        where ss.is_delete=0 " +
                                        "        and ss.sales_supplier_pickup_plan_payment_id=sales_supplier_pickup_plan_payment_id) " +
                                        "        )as settlement_amount, " +
                                        "       (select (a.total_weight-(a.total_number*(select gpscg.supply_chain_goods_package_weight from goods_parameter_supply_chain_goods gpscg  where gpscg.is_delete=0 and gpscg.id=a.goods_parameter_supply_chain_goods_id))) as weight " +
                                        "  from sales_supplier_pickup_goods_inspect_accept_detail a " +
                                        "  where a.is_delete=0 " +
                                        "   and a.id=sales_supplier_pickup_goods_inspect_accept_detail_id ) as accept_total_weight, " +
                                        "    (select sppc.real_settlement_price " +
                                        "        from sales_pickup_plan_command sppc " +
                                        "            where sppc.is_delete=0 " +
                                        "            and sppc.id = " +
                                        "        (select a.sales_pickup_plan_command_id " +
                                        "     from sales_supplier_pickup_goods_inspect_accept_detail a " +
                                        "     where a.is_delete=0 " +
                                        "       and a.id=b.sales_supplier_pickup_goods_inspect_accept_detail_id)) as real_settlement_price" +
                                        " from sales_supplier_warehouse_payment_diff b " +
                                        " where b.is_delete=0 and b.supplier_id=$1 " +
                                        "  and b.generate_date >= '"+dates.get(0)+"' " +
                                        "  and b.generate_date < '"+dates.get(1)+"' " +
                                        "  and b.supplier_warehouse_payment_diff_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        ") ";
                                Future<JsonArray> getDetitleFuture8 = this.commonRepository.queryJsonArray(conn, d_sql8,Tuple.of(supplier_id), "销售区-供应商入库通知单支付差异单 操作失败");
                                futureList.add(getDetitleFuture8);

                                //销售区-供应商赔偿单
                                String d_sql9 = "select b.aggregation_id,b.unqualify_compensation_affirm_amount,b.supplier_compensation_code " +
                                        " from sales_supplier_compensation b " +
                                        " where b.is_delete=0 and b.supplier_id=$1 " +
                                        "  and b.generate_date >= '"+dates.get(0)+"' " +
                                        "  and b.generate_date < '"+dates.get(1)+"' " +
                                        "  and b.supplier_compensation_code not in ( " +
                                        "    select payment_order_code " +
                                        "    from supplier_invoicing_management_detail " +
                                        "    where 1=1 " +
                                        ") ";
                                Future<JsonArray> getDetitleFuture9 = this.commonRepository.queryJsonArray(conn, d_sql9,Tuple.of(supplier_id), "销售区-供应商赔偿单 操作失败");
                                futureList.add(getDetitleFuture9);

                                // 并行执行多个future
                                CompositeFuture.join(futureList).onComplete(ar -> {
                                    if (ar.succeeded()) {
                                        String goods_gather_area_name = ar.result().list().get(0).toString();
                                        String supplier_name = ar.result().list().get(1).toString();
                                        String exist_seq = ar.result().list().get(2).toString();
                                        JsonArray recordsJSArray3 = (JsonArray) ar.result().list().get(3);
                                        JsonArray recordsJSArray8 = (JsonArray) ar.result().list().get(8);
                                        double total_taxable_sales_amount_demand_orders=0.00;
                                        List<Tuple> tupleList =new ArrayList<>();
                                        if (recordsJSArray3.size()>0){
                                            //计算
                                            for (int i =0;i<recordsJSArray3.size();i++){
                                                JsonObject record_obj3 = recordsJSArray3.getJsonObject(i);
                                                double payment_total_amount = Double.parseDouble(record_obj3.getString("payment_total_amount"));
                                                BigDecimal bigDecimal1 =new BigDecimal(payment_total_amount);
                                                BigDecimal bigDecimal = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                                total_taxable_sales_amount_demand_orders =bigDecimal.add(bigDecimal1).doubleValue();
                                            }
                                            JsonArray recordsJSArray4 = (JsonArray) ar.result().list().get(4);
                                            if (recordsJSArray4.size()>0){
                                                for (int i =0;i<recordsJSArray4.size();i++){
                                                    JsonObject record_obj4 = recordsJSArray4.getJsonObject(i);
                                                    double real_pickup_number = Double.parseDouble(record_obj4.getString("real_pickup_number"));
                                                    BigDecimal bigDecimal01 =new BigDecimal(real_pickup_number);
                                                    double real_settlement_package_spec = Double.parseDouble(record_obj4.getString("real_settlement_package_spec"));
                                                    BigDecimal bigDecimal02 =new BigDecimal(real_settlement_package_spec);
                                                    double settlement_price = Double.parseDouble(record_obj4.getString("settlement_price"));
                                                    BigDecimal bigDecimal03 =new BigDecimal(settlement_price);
                                                    double real_goods_grade_pickup_plan_number = Double.parseDouble(record_obj4.getString("real_goods_grade_pickup_plan_number"));
                                                    BigDecimal bigDecimal04 =new BigDecimal(real_goods_grade_pickup_plan_number);

                                                    BigDecimal bigDecimal05 =bigDecimal01.multiply(bigDecimal02).multiply(bigDecimal03);
                                                    BigDecimal bigDecimal06 =bigDecimal04.multiply(bigDecimal02).multiply(bigDecimal03);

                                                    BigDecimal bigDecimal1 =bigDecimal05.subtract(bigDecimal06);
                                                    BigDecimal bigDecimal = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                                    total_taxable_sales_amount_demand_orders =bigDecimal.subtract(bigDecimal1).doubleValue();
                                                }
                                            }
                                            JsonArray recordsJSArray5 = (JsonArray) ar.result().list().get(5);
                                            if (recordsJSArray5.size()>0){
                                                for (int i =0;i<recordsJSArray5.size();i++){
                                                    JsonObject record_obj5 = recordsJSArray5.getJsonObject(i);
                                                    double price = Double.parseDouble(record_obj5.getString("settlement_price"));
                                                    double weight = Double.parseDouble(record_obj5.getString("unqualify_goods_weight"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(price);
                                                    BigDecimal bigDecimal2 =new BigDecimal(weight);
                                                    BigDecimal bigDecimal = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                                    total_taxable_sales_amount_demand_orders =bigDecimal.subtract(bigDecimal1.multiply(bigDecimal2)).doubleValue();
                                                }
                                            }
                                            JsonArray recordsJSArray6 = (JsonArray) ar.result().list().get(6);
                                            if (recordsJSArray6.size()>0){
                                                for (int i =0;i<recordsJSArray6.size();i++){
                                                    JsonObject record_obj = recordsJSArray6.getJsonObject(i);
                                                    double all_amount = Double.parseDouble(record_obj.getString("payment_total_amount"));
                                                    double weight = Double.parseDouble(record_obj.getString("accept_total_weight"));
                                                    double settlement_price = Double.parseDouble(record_obj.getString("settlement_price"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(all_amount);
                                                    BigDecimal bigDecimal2 =new BigDecimal(weight);
                                                    BigDecimal bigDecimal3 =new BigDecimal(settlement_price);
                                                    BigDecimal bigDecimal = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                                    total_taxable_sales_amount_demand_orders =bigDecimal.subtract(bigDecimal2.multiply(bigDecimal3).subtract(bigDecimal1)).doubleValue();
                                                }
                                            }
                                            JsonArray recordsJSArray7 = (JsonArray) ar.result().list().get(7);
                                            if (recordsJSArray6.size()>0){
                                                for (int i =0;i<recordsJSArray7.size();i++){
                                                    JsonObject record_obj = recordsJSArray7.getJsonObject(i);
                                                    double amount = Double.parseDouble(record_obj.getString("unqualify_compensation_affirm_amount"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(amount);
                                                    BigDecimal bigDecimal = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                                    total_taxable_sales_amount_demand_orders =bigDecimal.subtract(bigDecimal1).doubleValue();
                                                }
                                            }

                                        }else if (recordsJSArray8.size()>0){
                                            if (recordsJSArray8.size()>0){
                                                for (int i =0;i<recordsJSArray8.size();i++){
                                                    JsonObject record_obj = recordsJSArray8.getJsonObject(i);
                                                    double amount = Double.parseDouble(record_obj.getString("payment_total_amount"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(amount);
                                                    BigDecimal bigDecimal = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                                    total_taxable_sales_amount_demand_orders =bigDecimal.add(bigDecimal1).doubleValue();
                                                }
                                            }
                                            JsonArray recordsJSArray9 = (JsonArray) ar.result().list().get(9);
                                            if (recordsJSArray9.size()>0){
                                                for (int i =0;i<recordsJSArray9.size();i++){
                                                    JsonObject record_obj = recordsJSArray9.getJsonObject(i);
                                                    double price = Double.parseDouble(record_obj.getString("real_settlement_price"));
                                                    double weight = Double.parseDouble(record_obj.getString("unqualify_goods_weight"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(price);
                                                    BigDecimal bigDecimal2 =new BigDecimal(weight);
                                                    BigDecimal bigDecimal = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                                    total_taxable_sales_amount_demand_orders =bigDecimal.subtract(bigDecimal1.multiply(bigDecimal2)).doubleValue();
                                                }
                                            }
                                            JsonArray recordsJSArray10 = (JsonArray) ar.result().list().get(10);
                                            if (recordsJSArray10.size()>0){
                                                for (int i =0;i<recordsJSArray10.size();i++){
                                                    JsonObject record_obj = recordsJSArray10.getJsonObject(i);
                                                    double all_amount = Double.parseDouble(record_obj.getString("payment_total_amount"));
                                                    double weight = Double.parseDouble(record_obj.getString("accept_total_weight"));
                                                    double price = Double.parseDouble(record_obj.getString("real_settlement_price"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(all_amount);
                                                    BigDecimal bigDecimal2 =new BigDecimal(weight);
                                                    BigDecimal bigDecimal3 =new BigDecimal(price);
                                                    BigDecimal bigDecimal = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                                    total_taxable_sales_amount_demand_orders =bigDecimal.subtract(bigDecimal2.multiply(bigDecimal3).subtract(bigDecimal1)).doubleValue();
                                                }
                                            }
                                            JsonArray recordsJSArray11 = (JsonArray) ar.result().list().get(11);
                                            if (recordsJSArray11.size()>0){
                                                for (int i =0;i<recordsJSArray11.size();i++){
                                                    JsonObject record_obj = recordsJSArray11.getJsonObject(i);
                                                    double amount = Double.parseDouble(record_obj.getString("unqualify_compensation_affirm_amount"));
                                                    BigDecimal bigDecimal1 =new BigDecimal(amount);
                                                    BigDecimal bigDecimal = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                                    total_taxable_sales_amount_demand_orders =bigDecimal.subtract(bigDecimal1).doubleValue();
                                                }
                                            }
                                        }else {
                                            //聚合或者销售区的相关明细数据都不存在则不能新增报错
                                            promise.fail(CommonUtils.createExceptionJsonObjectStr(ar, "insert", "新增失败！没有找到聚集区或者销售区的供应商提货计划支付单"));
                                        }

                                        int[] seqs = new int[1];
                                        int new_seq = 101;
                                        // 为新 new_method_code 赋值
                                        if (!exist_seq.equals("")) {
                                            new_seq = Integer.parseInt(exist_seq) + 1;
                                        }
                                        seqs[0] = new_seq;
                                        String invoicing_document_code = GenerateOrderNumberUtils.getWithdrawalPlan2("KPXQ",goods_gather_area_name,supplier_name,seqs[0]);

                                        //明细
                                        JsonArray recordsJSArray12 = (JsonArray) ar.result().list().get(12);
                                        if (recordsJSArray12.size()>0){
                                            for (int i =0;i<recordsJSArray12.size();i++){
                                                JsonObject record_obj = recordsJSArray12.getJsonObject(i);
                                                String payment_order_code = record_obj.getString("supplier_pickup_plan_payment_code");
                                                Integer aggregation_id = Integer.valueOf(record_obj.getString("aggregation_id"));
                                                double real_payment_amount = Double.parseDouble(record_obj.getString("real_payment_amount"));
                                                Tuple tuple=Tuple.of(legal_entity_id,invoicing_document_code,invoicing_cycle_id,1,payment_order_code,aggregation_id,
                                                        real_payment_amount, create_user,create_user);
                                                tupleList.add(tuple);
                                            }
                                        }

                                        JsonArray recordsJSArray13 = (JsonArray) ar.result().list().get(13);
                                        if (recordsJSArray13.size()>0){
                                            for (int i =0;i<recordsJSArray13.size();i++){
                                                JsonObject record_obj = recordsJSArray13.getJsonObject(i);
                                                String supplier_pickup_plan_payment_difference_code = record_obj.getString("supplier_pickup_plan_payment_difference_code");
                                                Integer aggregation_id = Integer.valueOf(record_obj.getString("aggregation_id"));
                                                double payment_difference_amount = Double.parseDouble(record_obj.getString("payment_difference_amount"));
                                                Tuple tuple=Tuple.of(legal_entity_id,invoicing_document_code,invoicing_cycle_id,2,supplier_pickup_plan_payment_difference_code,aggregation_id,
                                                        payment_difference_amount, create_user,create_user);
                                                tupleList.add(tuple);
                                            }
                                        }

                                        JsonArray recordsJSArray14 = (JsonArray) ar.result().list().get(14);
                                        if (recordsJSArray14.size()>0){
                                            for (int i =0;i<recordsJSArray14.size();i++){
                                                JsonObject record_obj = recordsJSArray14.getJsonObject(i);
                                                String code = record_obj.getString("supplier_return_notice_payment_diff_code");
                                                Integer aggregation_id = Integer.valueOf(record_obj.getString("aggregation_id"));
                                                double settlement_price = Double.parseDouble(record_obj.getString("settlement_price"));
                                                double unqualify_goods_weight = Double.parseDouble(record_obj.getString("unqualify_goods_weight"));
                                                BigDecimal bigDecimal1= new BigDecimal(settlement_price);
                                                BigDecimal bigDecimal2= new BigDecimal(unqualify_goods_weight);
                                                double amount =bigDecimal1.multiply(bigDecimal2).doubleValue();
                                                Tuple tuple=Tuple.of(legal_entity_id,invoicing_document_code,invoicing_cycle_id,3,code,aggregation_id,
                                                        amount, create_user,create_user);
                                                tupleList.add(tuple);
                                            }
                                        }


                                        JsonArray recordsJSArray15 = (JsonArray) ar.result().list().get(15);
                                        if (recordsJSArray15.size()>0){
                                            for (int i =0;i<recordsJSArray15.size();i++){
                                                JsonObject record_obj = recordsJSArray15.getJsonObject(i);
                                                String code = record_obj.getString("supplier_warehouse_payment_diff_code");
                                                Integer aggregation_id = Integer.valueOf(record_obj.getString("aggregation_id"));
                                                double payment_total_amount = Double.parseDouble(record_obj.getString("payment_total_amount"));
                                                double accept_total_weight = Double.parseDouble(record_obj.getString("accept_total_weight"));
                                                double settlement_price = Double.parseDouble(record_obj.getString("settlement_price"));
                                                BigDecimal bigDecimal1=new BigDecimal(payment_total_amount);
                                                BigDecimal bigDecimal2=new BigDecimal(accept_total_weight);
                                                BigDecimal bigDecimal3=new BigDecimal(settlement_price);
                                                double amount=bigDecimal2.multiply(bigDecimal3).subtract(bigDecimal1).doubleValue();
                                                Tuple tuple=Tuple.of(legal_entity_id,invoicing_document_code,invoicing_cycle_id,4,code,aggregation_id,
                                                        amount, create_user,create_user);
                                                tupleList.add(tuple);
                                            }
                                        }

                                        JsonArray recordsJSArray16 = (JsonArray) ar.result().list().get(16);
                                        if (recordsJSArray16.size()>0){
                                            for (int i =0;i<recordsJSArray16.size();i++){
                                                JsonObject record_obj = recordsJSArray16.getJsonObject(i);
                                                String code = record_obj.getString("supplier_compensation_code");
                                                Integer aggregation_id = Integer.valueOf(record_obj.getString("aggregation_id"));
                                                double payment_difference_amount = Double.parseDouble(record_obj.getString("unqualify_compensation_affirm_amount"));
                                                Tuple tuple=Tuple.of(legal_entity_id,invoicing_document_code,invoicing_cycle_id,5,code,aggregation_id,
                                                        payment_difference_amount, create_user,create_user);
                                                tupleList.add(tuple);
                                            }
                                        }

                                        JsonArray recordsJSArray17 = (JsonArray) ar.result().list().get(17);
                                        if (recordsJSArray17.size()>0){
                                            for (int i =0;i<recordsJSArray17.size();i++){
                                                JsonObject record_obj = recordsJSArray17.getJsonObject(i);
                                                String code = record_obj.getString("supplier_pickup_plan_payment_code");
                                                Integer aggregation_id = Integer.valueOf(record_obj.getString("aggregation_id"));
                                                double payment_difference_amount = Double.parseDouble(record_obj.getString("settlement_amount"));
                                                Tuple tuple=Tuple.of(legal_entity_id,invoicing_document_code,invoicing_cycle_id,6,code,aggregation_id,
                                                        payment_difference_amount, create_user,create_user);
                                                tupleList.add(tuple);
                                            }
                                        }

                                        JsonArray recordsJSArray18 = (JsonArray) ar.result().list().get(18);
                                        if (recordsJSArray18.size()>0){
                                            for (int i =0;i<recordsJSArray18.size();i++){
                                                JsonObject record_obj = recordsJSArray18.getJsonObject(i);
                                                String code = record_obj.getString("supplier_return_notice_payment_diff_code");
                                                Integer aggregation_id = Integer.valueOf(record_obj.getString("aggregation_id"));
                                                double return_goods_total_weight = Double.parseDouble(record_obj.getString("return_goods_total_weight"));
                                                double real_settlement_price = Double.parseDouble(record_obj.getString("real_settlement_price"));
                                                BigDecimal bigDecimal1 =new BigDecimal(return_goods_total_weight);
                                                BigDecimal bigDecimal2 =new BigDecimal(real_settlement_price);
                                                double payment_difference_amount = bigDecimal1.multiply(bigDecimal2).doubleValue();
                                                Tuple tuple=Tuple.of(legal_entity_id,invoicing_document_code,invoicing_cycle_id,7,code,aggregation_id,
                                                        payment_difference_amount, create_user,create_user);
                                                tupleList.add(tuple);
                                            }
                                        }

                                        JsonArray recordsJSArray19 = (JsonArray) ar.result().list().get(19);
                                        if (recordsJSArray19.size()>0){
                                            for (int i =0;i<recordsJSArray19.size();i++){
                                                JsonObject record_obj = recordsJSArray19.getJsonObject(i);
                                                String code = record_obj.getString("supplier_warehouse_payment_diff_code");
                                                Integer aggregation_id = Integer.valueOf(record_obj.getString("aggregation_id"));
                                                double settlement_amount = Double.parseDouble(record_obj.getString("settlement_amount"));
                                                double accept_total_weight = Double.parseDouble(record_obj.getString("accept_total_weight"));
                                                double real_settlement_price = Double.parseDouble(record_obj.getString("real_settlement_price"));
                                                BigDecimal bigDecimal1=new BigDecimal(settlement_amount);
                                                BigDecimal bigDecimal2=new BigDecimal(accept_total_weight);
                                                BigDecimal bigDecimal3=new BigDecimal(real_settlement_price);
                                                double payment_difference_amount =bigDecimal2.multiply(bigDecimal3).subtract(bigDecimal1).doubleValue();
                                                Tuple tuple=Tuple.of(legal_entity_id,invoicing_document_code,invoicing_cycle_id,8,code,aggregation_id,
                                                        payment_difference_amount, create_user,create_user);
                                                tupleList.add(tuple);
                                            }
                                        }
                                        JsonArray recordsJSArray20 = (JsonArray) ar.result().list().get(20);
                                        if (recordsJSArray20.size()>0){
                                            for (int i =0;i<recordsJSArray20.size();i++){
                                                JsonObject record_obj = recordsJSArray20.getJsonObject(i);
                                                String code = record_obj.getString("supplier_compensation_code");
                                                Integer aggregation_id = Integer.valueOf(record_obj.getString("aggregation_id"));
                                                double payment_difference_amount = Double.parseDouble(record_obj.getString("unqualify_compensation_affirm_amount"));
                                                Tuple tuple=Tuple.of(legal_entity_id,invoicing_document_code,invoicing_cycle_id,9,code,aggregation_id,
                                                        payment_difference_amount, create_user,create_user);
                                                tupleList.add(tuple);
                                            }
                                        }


                                        BigDecimal bigDecimal1 = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                        BigDecimal bigDecimal2 = new BigDecimal(demand_order_input_tax_rate);
                                        double demand_order_input_tax_amount=bigDecimal1.multiply(bigDecimal2).doubleValue();
//                                        double online_cumulative_demand_order_input_tax_amount=0.00;
                                        BigDecimal bigDecimal3=new BigDecimal(total_taxable_sales_invoices_amount);
                                        BigDecimal bigDecimal4=new BigDecimal(invoice_input_tax_rate);
                                        double invoice_input_tax_amount=bigDecimal3.multiply(bigDecimal4).doubleValue();
//                                        double online_cumulative_invoice_input_tax_amount=0.00;
//                                        BigDecimal bigDecimal5= new BigDecimal(online_cumulative_demand_order_input_tax_amount);
//                                        BigDecimal bigDecimal6= new BigDecimal(online_cumulative_invoice_input_tax_amount);
//                                        double accumulated_difference_input_tax_payable=bigDecimal6.subtract(bigDecimal5).doubleValue();

                                        List<Future> futureList1 = new ArrayList<>();
                                        if (tupleList.size()>0){
                                            String insert_sql = "INSERT INTO supplier_invoicing_management(goods_gather_area_id,supplier_id,legal_entity_id,invoicing_document_code,invoicing_cycle_id, " +
                                                    "total_taxable_sales_amount_demand_orders,demand_order_input_tax_rate,demand_order_input_tax_amount," +
                                                    "input_tax_invoice_code,total_taxable_sales_invoices_amount," +
                                                    "invoice_input_tax_rate,invoice_input_tax_amount,create_user,update_user,seq) " +
                                                    "VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15) RETURNING id";
                                            long a1 = create_user;
                                            String a2 = String.valueOf(seqs[0]);
                                            Future future = this.commonRepository.insertOrUpdate(conn, insert_sql, Tuple.of(goods_gather_area_id, supplier_id, legal_entity_id,invoicing_document_code , invoicing_cycle_id,
                                                    total_taxable_sales_amount_demand_orders,demand_order_input_tax_rate,demand_order_input_tax_amount,
                                                    input_tax_invoice_code,total_taxable_sales_invoices_amount,invoice_input_tax_rate,invoice_input_tax_amount,
                                                    a1, a1,a2), "insert_sql");
                                            futureList1.add(future);
                                            String insert_sql2 = "INSERT INTO supplier_invoicing_management_detail(legal_entity_id,invoicing_document_code,invoicing_cycle_id, " +
                                                    "payment_order_type_id,payment_order_code,aggregation_id," +
                                                    "payment_amount,create_user,update_user) " +
                                                    "VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9) RETURNING id";

                                            Future future2 = this.commonRepository.insertOrUpdateBatch(conn, insert_sql2, tupleList, "insert_sql2");
                                            futureList1.add(future2);

                                            CompositeFuture.join(futureList1)
                                                    .onComplete(ar10 -> {
                                                        if (ar10.succeeded()){
                                                            responseJSObj.put("code",200).put("msg", "新增成功!");
                                                            this.commonRepository.writePlatformLog(conn, user_id, "/web/supplier_invoicing_management/insert", bodyJSObj, responseJSObj, "")
                                                                    .onComplete(ar4 -> {
                                                                        promise.complete(responseJSObj);
                                                                    });
                                                        }else {
                                                            promise.fail(CommonUtils.createExceptionJsonObjectStr(ar3, "insert", "新增失败！"+ar10.cause()));
                                                        }
                                                    }).onFailure(error->promise.fail(CommonUtils.createExceptionJsonObjectStr(error, "insert", "新增失败失败"+error.getMessage())));
                                        }else {
                                            promise.fail(CommonUtils.createExceptionJsonObjectStr(ar, "getInvoiceCycleFuture", "没有查询到对应的明细，所以无法新增头和明细"));
                                        }
                                    }else {
                                        //查询失败
                                        promise.fail(CommonUtils.createExceptionJsonObjectStr(ar, "getInvoiceCycleFuture", "查询开票周期数据发生错误:原因"+ar.cause()));
                                    }
                                });

                            }else {
                                //查询失败
                                promise.fail(CommonUtils.createExceptionJsonObjectStr(ar3, "getInvoiceCycleFuture", "查询开票周期数据发生错误"));
                            }
                        }).onFailure(err -> promise.fail(CommonUtils.createExceptionJsonObjectStr(err, "getInvoiceCycleFuture", "数据库连接失败")));

            }else if (method.equals("update")) {

                // 获取bodyJSObj参数对象中字段的值
                long id = Long.valueOf(bodyJSObj.getString("id"));
                Long legal_entity_id = Long.parseLong(bodyJSObj.getString("legal_entity_id"));
                String input_tax_invoice_code= bodyJSObj.getString("input_tax_invoice_code");
                double demand_order_input_tax_rate = Double.parseDouble(bodyJSObj.getString("demand_order_input_tax_rate"));
                double total_taxable_sales_invoices_amount = Double.parseDouble(bodyJSObj.getString("total_taxable_sales_invoices_amount"));
                double invoice_input_tax_rate = Double.parseDouble(bodyJSObj.getString("invoice_input_tax_rate"));
                // 并行执行多个future
                List<Future> futureList = new ArrayList<>();
                String supplier_invoicing_management_sql = "select total_taxable_sales_amount_demand_orders from supplier_invoicing_management where id = $1  limit 1";
                Future<String> simFuture = this.commonRepository.getCodeFuture2(conn, supplier_invoicing_management_sql, Tuple.of(id),"supplier_invoicing_management_sql", "供应商开票管理主表 操作失败");
                futureList.add(simFuture);
                CompositeFuture.join(futureList)
                        .onComplete(ar -> {
                            if (ar.succeeded()) {
                                String a = ar.result().list().get(0).toString();
                                    double total_taxable_sales_amount_demand_orders = Double.parseDouble(a);
                                    BigDecimal bigDecimal1 = new BigDecimal(total_taxable_sales_amount_demand_orders);
                                    BigDecimal bigDecimal2 = new BigDecimal(demand_order_input_tax_rate);
                                    double demand_order_input_tax_amount=bigDecimal1.multiply(bigDecimal2).doubleValue();
//                                    double online_cumulative_demand_order_input_tax_amount=0.00;
                                    BigDecimal bigDecimal3=new BigDecimal(total_taxable_sales_invoices_amount);
                                    BigDecimal bigDecimal4=new BigDecimal(invoice_input_tax_rate);
                                    double invoice_input_tax_amount=bigDecimal3.multiply(bigDecimal4).doubleValue();
//                                    double online_cumulative_invoice_input_tax_amount=0.00;
//                                    BigDecimal bigDecimal5= new BigDecimal(online_cumulative_demand_order_input_tax_amount);
//                                    BigDecimal bigDecimal6= new BigDecimal(online_cumulative_invoice_input_tax_amount);
//                                    double accumulated_difference_input_tax_payable=bigDecimal6.subtract(bigDecimal5).doubleValue();
                                    List<Future> futureList1 = new ArrayList<>();
                                    String update_sql = "UPDATE supplier_invoicing_management SET total_taxable_sales_amount_demand_orders= $1,demand_order_input_tax_rate= $2,legal_entity_id= $3,update_user = $4 , " +
                                            " demand_order_input_tax_amount=$5  , input_tax_invoice_code=$6 , " +
                                            " total_taxable_sales_invoices_amount=$7 , invoice_input_tax_rate=$8 , invoice_input_tax_amount=$9  WHERE id = $10 RETURNING id";
                                    Future future1 = this.commonRepository.insertOrUpdate(conn, update_sql, Tuple.of(total_taxable_sales_amount_demand_orders, demand_order_input_tax_rate, legal_entity_id, create_user,
                                                    demand_order_input_tax_amount,input_tax_invoice_code,total_taxable_sales_invoices_amount,invoice_input_tax_rate,invoice_input_tax_amount,id), "update_supplier_invoicing_management");
                                    futureList1.add(future1);
                                    long a2= create_user;
                                    String update_sql2="UPDATE supplier_invoicing_management_detail SET legal_entity_id=$1,update_user=$2 where id=$3";
                                    Future future2 = this.commonRepository.insertOrUpdate(conn, update_sql2, Tuple.of(legal_entity_id,a2,id), "update_supplier_invoicing_management_detail");
                                    futureList1.add(future2);
                                    CompositeFuture.join(futureList1).onComplete(ar11->{
                                        if (ar11.succeeded()){
                                            responseJSObj.put("code",200).put("msg", "更新成功!");
                                            this.commonRepository.writePlatformLog(conn, user_id, "/web/supplier_invoicing_management/update", bodyJSObj, responseJSObj, "")
                                                    .onComplete(ar3 -> {
                                                        promise.complete(responseJSObj);
                                                    });
                                        }else {
                                            promise.fail(CommonUtils.createExceptionJsonObjectStr(ar, "updateSupplierInvoicingManagementDetail", "更新数据发生错误"));
                                        }
                                    }).onFailure(error->promise.fail(CommonUtils.createExceptionJsonObjectStr(error, "updateSupplierInvoicingManagementDetail", "更新数据失败"+error.getMessage())));
                            } else {
                                promise.fail(CommonUtils.createExceptionJsonObjectStr(ar, "updateSupplierInvoicingManagementDetail", "查询数据发生错误"));
                            }
                        });
            }
        }).onFailure(err -> promise.fail(CommonUtils.createExceptionJsonObjectStr(err, "SupplierInvoicingManagement", "数据库连接失败")));
        return promise.future();
    }



    /**
     * 根据传入的查询参数获取满足条件的记录
     *
     * @param client
     * @param config
     * @param bodyJSObj
     * @return
     */
    public Future<JsonObject> getDetailRecords(PgPool client, JsonObject config, JsonObject bodyJSObj) {
        Promise<JsonObject> promise = Promise.promise();
        //最后返回的JsonObject对象
        JsonObject responseJSObj = new JsonObject();
        // 验证必须传递的字段
        List<String> must_fields = Arrays.asList( "invoicing_document_code");
        JsonObject must = this.commonRepository.verifyAllParamMust(bodyJSObj, must_fields);
        if (must != null) {
            promise.complete(must);
            return promise.future();
        }
        //从bodyJson中获取数据
        String invoicing_document_code = bodyJSObj.getString("invoicing_document_code");
        //数据是否为空校验
        if (DataUtils.isEmpty(invoicing_document_code)) {
            promise.fail(CommonUtils.createExceptionJsonObjectStr(408, "参数 不合法"));
            return promise.future();
        }
        //用于传递给构建sql的JsonObject
        JsonObject queryJSObj = new JsonObject();
        queryJSObj.put("invoicing_document_code", invoicing_document_code);

        this.commonRepository.getCon(client).onSuccess(conn -> {
            String sql = createSelectSql2(queryJSObj);
            this.commonRepository.queryJsonArray(conn, sql, "getSupplierInvoicingManagementDetailRecords")
                    .onSuccess(resJSArray -> { //resJSArray中就是获取到符合条件的数据
                        //获取满足条件的记录总数
                        String count_sql = this.commonRepository.createCountSql(queryJSObj, "supplier_invoicing_management_detail");
                        Future<Integer> getTotalFuture = this.commonRepository.getRecordsCount(conn, count_sql, "get_supplier_invoicing_management_detail_totle");
                        CompositeFuture.join(Arrays.asList(getTotalFuture)).onComplete(ar2 -> {
                            if (ar2.succeeded()) {
                                int total_records = Integer.valueOf(ar2.result().list().get(0).toString());
                                JsonObject dataJSObj = new JsonObject();
                                dataJSObj.put("total", total_records).put("records", resJSArray);
                                responseJSObj.put("code", 200).put("msg", "获取记录成功").put("data", dataJSObj);
                                promise.complete(responseJSObj);
                            } else {
                                logger.info("获取记录数据发生错误: {}", ar2.cause().getMessage());
                                promise.complete(CommonUtils.createExceptionJsonObject(ar2, "getSupplierInvoicingManagementDetailRecords", "获取供应商开票管理明细失败"));
                            }
                        });
                    }).onFailure(err -> promise.complete(CommonUtils.createExceptionJsonObject(err, "getSupplierInvoicingManagementDetailRecords", "获取供应商开票管理明细失败")));
        }).onFailure(err -> promise.fail(CommonUtils.createJsonObject(err, "getSupplierInvoicingManagementDetailRecords", "数据库连接失败")));
        return promise.future();
    }


    /**
     * 创建查询符合搜索条件记录的sql语句
     *
     * @param queryJS      body参数对象
     * @return 查询符合搜索条件的sql语句
     */
    public String createSelectSql2(JsonObject queryJS) {
        SelectQuery sq = new SelectQuery();
        sq.addCustomColumns(new CustomSql("id"), new CustomSql("invoicing_document_code"), new CustomSql("invoicing_cycle_id"),new CustomSql("legal_entity_id"),new CustomSql("  (select pe.legal_entity_name " +
                                "        from payment_entity pe " +
                                "        where pe.is_delete=0 " +
                                "        and pe.id=legal_entity_id) as legal_entity_name"),new CustomSql("payment_order_type_id"),new CustomSql("(case " +
                                "    when payment_order_type_id=1 then  '计划支付单' " +
                                "    when payment_order_type_id=2 then  '计划支付异常单' " +
                                "    when payment_order_type_id=3 then  '退货支付异常单' " +
                                "    when payment_order_type_id=4 then  '入库支付异常单' " +
                                "    when payment_order_type_id=5 then  '供应商赔偿单' " +
                                "    when payment_order_type_id=6 then  '销售地区计划支付单' " +
                                "    when payment_order_type_id=7 then  '销售地区退货支付异常单' " +
                                "    when payment_order_type_id=8 then  '销售地区入库支付异常单' " +
                                "    when payment_order_type_id=9 then  '销售地区供应商赔偿单' " +
                                "    end ) as payment_order_type_name"),new CustomSql("payment_order_code"),
                        new CustomSql("aggregation_id"), new CustomSql("  (select aggregation_name " +
                                "        from aggregation_goods " +
                                "        where is_delete=0 " +
                                "        and id=aggregation_id)as aggregation_name"),new CustomSql("payment_amount"),
                        new CustomSql("create_user"), new CustomSql("update_user"), new CustomSql("create_time"), new CustomSql("update_time"))
                .addCustomFromTable("supplier_invoicing_management_detail");
        Iterator<String> iter = queryJS.fieldNames().iterator();
        while (iter.hasNext()) {
            String key = iter.next();
            try {
                String value = queryJS.getString(key);
                if (!value.equals("") && !value.equals("[]") && !value.equals("[all]")) {
                    String firstChar = value.substring(0, 1);
                    if (firstChar.equals("["))
                        value = value.substring(1, value.length() - 1);
                    value = value.replace(", ", "','");
                    // 添加where InCondtion子句
                    sq.getWhereClause().addCustomCondition(new InCondition(new CustomSql(key), value));
                }
            } catch (Exception e) {
                logger.info("createSql, 发生错误,错误原因: ", e.getMessage());
            }
        }
        return sq.validate() + " order by id desc ";
    }

}